import {
  storeCommit,
  getStoreData
} from "../libs/wxminiSharedData.js";
import {
  atob
} from "../libs/base64.min.js";
const loginStoragePrefix = "LOGIN_USER_TOKEN"; // 通过该key从缓存中读取/设置当前登录用户token

/**
 * 获取登录token
 * @return 失败或无，返回空字符串 getJwt()==="";成功返回内容
 */
const getJwt = () => {
  try {
    var value = wx.getStorageSync(loginStoragePrefix)
    if (value) {
      return value;
    } else {
      return "";
    }
  } catch (e) {
    return "";
  }
}

/**
 * 设置用户登录token
 * @param {string} token 用户登录成功的token
 * @return 成功返回true,失败返回false
 */
const setJwt = (token) => {
  try {
    wx.setStorageSync(loginStoragePrefix, token);
    storeCommit("setIsLogin", true);
    return true;
  } catch (e) {
    return false;
  }
}

/**
 * 判断用户是否已登录
 * 已登录且token有效返回true
 */
const hasJwt = () => {
  const jwt = getJwt();
  const has = jwt !== "" && !isExpire(jwt);
  if (!has) {
    removeJwt();
  } else {
    if (!getStoreData().isLogin) {
      storeCommit("setIsLogin", true);
    }
  }
  return has;
}

/**
 * 移除jwt
 */
const removeJwt = () => {
  try {
    wx.removeStorageSync(loginStoragePrefix);
  } catch (e) {} finally {
    storeCommit("setUserName", "登录/注册");
    storeCommit("setHead", "/public/images/default_avatar.png");
    storeCommit("setIsLogin", false);
  }
}

/**
 * 判断用户token是否过期
 * @return 返回true已过期，返回false有效
 */
const isExpire = (token) => {
  if (typeof token !== "string") {
    return false;
  }
  const t = token.split(".");
  if (t.length !== 3) {
    return false;
  }
  const time = JSON.parse(atob(t[1])).exp;
  if (time && +time < Date.parse(new Date()) / 1000) {
    return true;
  }
  return false;
}

module.exports = {
  getJwt,
  setJwt,
  hasJwt,
  removeJwt,
  isExpire
}